package cn.ubeta.b2c.utils;

import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * Created by liudengyong on 16/7/30.
 */

public class FileUtils {

    /**
     * 文件或者文件夹是否存在
     * @param fileName
     * @return
     */
    public static boolean exist(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }

    /**
     * 获取单个文件的MD5值！
     */
    public static String getFileMD5(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        return getFileMD5(new File(fileName));
    }

    /**
     * 获取单个文件的MD5值！
     */
    public static String getFileMD5(File file) {
        if (file == null || !file.exists() || !file.isFile()) {
            return null;
        }
        MessageDigest digest;
        FileInputStream in;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    /**
     * 删除文件
     * @param path
     */
    public static void deleteFile(String path) {
        File file = new File(path);
        if (file.exists())
            file.delete();
    }
}
